package com.kimwu.rabbitmq.utils;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class TenantUtils {

    public static void listentPutTenantId(Message message) {
        MessageProperties messageProperties = message.getMessageProperties();
        String authorization = (String) messageProperties.getHeader("tenant_id");
        // 设置一个环境属性
        NonWebRequestAttributes request = new NonWebRequestAttributes();
        request.setAttribute("tenant_id", authorization, 0);
        RequestContextHolder.setRequestAttributes(request);
    }

    public static MessagePostProcessor servicePutTenantId() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
        MessagePostProcessor messagePostProcessor = message -> {
            message.getMessageProperties().setHeader("tenant_id", request.getHeader("tenant_id"));
            return message;
        };
        return messagePostProcessor;
    }

}
